package www.openteam.com.ui.business;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.cundong.recyclerview.EndlessRecyclerOnScrollListener;
import com.cundong.recyclerview.HeaderAndFooterRecyclerViewAdapter;

import java.util.ArrayList;

import butterknife.Bind;
import www.openteam.com.R;
import www.openteam.com.adapter.ProductAdapter;
import www.openteam.com.base.mBaseFragment;
import www.openteam.com.bean.CustomType;
import www.openteam.com.bean.InsertStatus;
import www.openteam.com.bean.ProductInfo;
import www.openteam.com.contract.business.EditProductInfoContract;
import www.openteam.com.presenter.business.EditProductInfoPresenter;
import www.openteam.com.tool.RecyclerViewStateUtils;
import www.openteam.com.tool.ToastUtil;
import www.openteam.com.ui.DetailedActivity;
import www.openteam.com.widget.LoadingFooter;

/**
 * Created by hyd on 2016/10/16.
 * 编辑产品信息
 */

public class EditProductInfoFragment extends mBaseFragment<EditProductInfoPresenter>
        implements EditProductInfoContract.EditProductInfoView {


    private ArrayList<ProductInfo.DataEntity> editProductInfos;
    private ArrayList<ProductInfo.DataEntity> editProducts;
    private ArrayList<CustomType.DataBean> materialTypelsts;
    private ArrayList<CustomType.DataBean> materialTs;
    private static int pageSize = 0;
    private final String TAG = "EditProductInfo";
    int i = 0;
    private HeaderAndFooterRecyclerViewAdapter mFooterRecyclerViewAapter = null;
    private ProductAdapter editProductInfoAdapter = null;
    Throwable throwable = null;
    FragmentManager fm;
    private ButtonInterface buttonInterface;
    @Bind(R.id.ed_1)
    EditText ed_1;
    @Bind(R.id.ed_2)
    EditText ed_2;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        detailGather = ((DetailedActivity) getActivity()).getDetailGather();
        fm = getActivity().getSupportFragmentManager();
    }


    private void setEditProductInfosAdapter() {
        if (editProductInfoAdapter == null) {
            editProductInfoAdapter = new ProductAdapter(getActivity());
            editProductInfoAdapter.addItems(editProductInfos);
            editProductInfoAdapter.addItemsM(materialTypelsts, getActivity());
            materialTs = (ArrayList<CustomType.DataBean>) materialTypelsts.clone();
            editProductInfoAdapter.buildProductInfoInRealize(new ProductAdapter.BuildProductInfoIn() {
                @Override
                public void newBuildProductInfo() {

                    buttonInterface.onclick(materialTs);
                }

                @Override
                public void updateProductInfo(ProductInfo.DataEntity production, int position) {
                    buttonInterface.clickUpdate(materialTs, production, position);
                }

                @Override
                public void deleteProductInfo(String code) {
                    mPresenter.deleteProductInfo(code);
                }
            });
            mFooterRecyclerViewAapter = new HeaderAndFooterRecyclerViewAdapter(editProductInfoAdapter);
            mRecyclerView.setAdapter(mFooterRecyclerViewAapter);
            RecyclerViewStateUtils.setFooterViewState(this.mRecyclerView, LoadingFooter.State.Normal);
        } else {
            mFooterRecyclerViewAapter.notifyDataSetChanged();
            editProductInfoAdapter.addItems(editProductInfos);
            editProductInfoAdapter.addItemsM(materialTypelsts, getContext());
            materialTs = (ArrayList<CustomType.DataBean>) materialTypelsts.clone();
            editProductInfoAdapter.buildProductInfoInRealize(new ProductAdapter.BuildProductInfoIn() {
                @Override
                public void newBuildProductInfo() {
                    buttonInterface.onclick(materialTs);
                }

                @Override
                public void updateProductInfo(ProductInfo.DataEntity production, int position) {
                    Log.d(TAG, "clickUpdate: jg");
                    buttonInterface.clickUpdate(materialTs, production, position);
                }

                @Override
                public void deleteProductInfo(String code) {
                    mPresenter.deleteProductInfo(code);
                }
            });
            RecyclerViewStateUtils.setFooterViewState(this.mRecyclerView, LoadingFooter.State.Normal);
        }
    }

    @Override
    public void onRefresh() {
        if ((mRecyclerView.getChildCount() > 0) &&
                (!getRdsno().isEmpty() || !getCode().isEmpty())) {
            mRecyclerView.removeAllViews();
            editProductInfos.clear();
            editProductInfoAdapter = null;
            editProducts.clear();
            materialTs.clear();
            mFooterRecyclerViewAapter = null;
            i = 0;
            mPresenter.queryProductInfo(getRdsno(), getCode(), 0);
            throwable = null;
            mSwipeRefresh.setRefreshing(false);
        } else if ((mRecyclerView.getChildCount() <= 0) && (!getRdsno().isEmpty() || !getCode().isEmpty())) {
            Log.d(TAG, "onRefresh: else if " + mRecyclerView.getChildCount());
            mRecyclerView.removeAllViews();
            editProductInfoAdapter = null;
            editProductInfos.clear();
            editProducts.clear();
            materialTs.clear();
            i = 0;
            mPresenter.queryProductInfo(getRdsno(), getCode(), 0);
            mSwipeRefresh.setRefreshing(false);
        } else if ((mRecyclerView.getChildCount() >= 0) && (mRecyclerView != null)
                && (mSwipeRefresh != null)) {
            i = 0;
            mRecyclerView.removeAllViews();
            editProductInfoAdapter = null;
            editProductInfos.clear();
            editProducts.clear();
            mPresenter.queryProductInfo(getRdsno(), getCode(), 0);
            mSwipeRefresh.setRefreshing(false);
        }
    }


    public EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {

        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);
            LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(mRecyclerView);
            if (state == LoadingFooter.State.Loading) {
                i++;
            }
            i++;
            if (throwable == null && (editProductInfos.size() % 10 == 0)) {

                editProductInfos = new ArrayList<ProductInfo.DataEntity>();
//                editProducts=new ArrayList<ProductInfo.DataEntity>();
                mPresenter.queryProductInfo(getRdsno(), getCode(), i);

                RecyclerViewStateUtils.
                        setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.Loading, null);
            } else if (throwable == null && (editProductInfos.size() % 10 != 0)) {
                //the end
                mPresenter.queryProductInfo(getRdsno(), getCode(), i);
                RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
                throwable = null;
            } else if (throwable != null) {
                //the end
                i = 0;
                RecyclerViewStateUtils.setFooterViewState(getActivity(),
                        mRecyclerView, REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
                throwable = null;
            }

        }
    };


    private View.OnClickListener mFooterClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.Loading, null);
            mPresenter.queryProductInfo(getRdsno(), getCode(), i);
        }
    };

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        TextView tv_1, tv_2;
        tv_1 = (TextView) view.findViewById(R.id.tv_1);
        tv_2 = (TextView) view.findViewById(R.id.tv_2);
        tv_1.setText(detail[0]);
        tv_2.setText(detail[1]);


        initSRView(view);
        mRecyclerView.addOnScrollListener(mOnScrollListener);
        measurementLayoutHeight();
    }


    /**
     * 按钮点击事件需要的方法
     */
    public void buttonSetOnclick(ButtonInterface buttonInterface) {
        this.buttonInterface = buttonInterface;
    }

    @Override
    protected void initData() {

    }


    @Override
    public void initSRView(View view) {
        super.initSRView(view);
        mSwipeRefresh = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_widget);
        mSwipeRefresh.setColorSchemeResources(R.color.colorPrimary, R.color.colorPrimaryDark, R.color.colorAccent);
        mSwipeRefresh.setOnRefreshListener(this);


        mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
        linearLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(linearLayoutManager);

    }

    @Override
    protected void initListener() {
        final Button query = (Button) view.findViewById(R.id.query_btn);
        query.setOnClickListener(new View.OnClickListener() {  //查询按钮
            @Override
            public void onClick(View v) {
                materialTypelsts = new ArrayList<CustomType.DataBean>();
                mPresenter.queryMaterialTypelst();
            }
        });
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void otherViewClick(View view) {

    }

    @Override
    protected EditProductInfoPresenter loadPresenter() {
        return new EditProductInfoPresenter();
    }

    /**
     * 按钮点击事件对应的接口
     */
    public interface ButtonInterface {
        void onclick(ArrayList<CustomType.DataBean> materialType);

        void clickUpdate(ArrayList<CustomType.DataBean> materialType, ProductInfo.DataEntity prod, int position);

    }

    @Override
    public String getRdsno() {
        return ed_1.getText().toString();
    }

    @Override
    public String getCode() {
        return ed_2.getText().toString();
    }

    @Override
    public void hideMTData(Throwable throwable) {
        RecyclerViewStateUtils.setFooterViewState(getActivity(), this.mRecyclerView, REQUEST_COUNT, LoadingFooter.State.NetWorkError, this.mFooterClick);
        ToastUtil.showToast(getActivity(), "暂无匹配数据");
    }

    @Override
    public void loadMTData(CustomType materialTypelst) {
        for (CustomType.DataBean mt : materialTypelst.getData()
                ) {
            materialTypelsts.add(mt);
        }
        if (editProductInfoAdapter == null) {
            editProductInfos = new ArrayList<ProductInfo.DataEntity>();
            editProducts = new ArrayList<ProductInfo.DataEntity>();
            mPresenter.queryProductInfo(getRdsno(), getCode(), pageSize);
        } else {
            editProductInfoAdapter.deleteItems(editProductInfos);
            mRecyclerView.removeAllViews();
            editProducts.clear();
            throwable = null;
            i = 0;
            editProductInfos.clear();
            onRefresh();
        }
    }

    @Override
    public void deletePIData(InsertStatus insertStatus) {
        onRefresh();
    }

    @Override
    public void failPIData(Throwable throwable) {
        ToastUtil.showToast(getContext(), "删除失败");
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        String code = ((DetailedActivity) getActivity()).getQueryCode();
        if (hidden == false && code != null) {
            Log.d(TAG, "onHiddenChanged: " + code);
            mRecyclerView.removeAllViews();
            editProductInfos.clear();
            editProductInfoAdapter = null;
            editProducts.clear();
            mFooterRecyclerViewAapter = null;
            mPresenter.queryProductInfo(code, "", 0);
        }
    }

    @Override
    public void loadPIData(ProductInfo productInfo) {
        for (ProductInfo.DataEntity pi : productInfo.getData()) {
            editProductInfos.add(pi);
            editProducts.add(pi);
        }
        setEditProductInfosAdapter();
    }

    @Override
    public void hidePIData(Throwable throwable) {
        this.throwable = throwable;
        if (throwable.getMessage().substring(throwable.getMessage().indexOf(":") + 2).equals("暂无合适的数据")) {
//            Log.d(TAG, "hideProgress:  bunull " + throwable.toString() + "---" + throwable.getMessage());
            RecyclerViewStateUtils.setFooterViewState(getActivity(),
                    mRecyclerView, REQUEST_COUNT,
                    LoadingFooter.State.TheEnd, null);
            ToastUtil.showToast(getActivity(), throwable.getMessage().substring(throwable.getMessage().indexOf(":") + 2));
        } else {
//            Log.d(TAG, "hideProgress:  esle " + throwable.toString() + "---" + throwable.getMessage().substring(throwable.getMessage().indexOf(":") + 1));
            RecyclerViewStateUtils.setFooterViewState(getActivity(), this.mRecyclerView, REQUEST_COUNT, LoadingFooter.State.NetWorkError, this.mFooterClick);
            ToastUtil.showToast(getActivity(), "网络连接有误");
        }
    }


}
